package com.huabo.monitor.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.enums.ProcessEnum;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.JsonBean;
import com.huabo.monitor.entity.TblAssessStaff;
import com.huabo.monitor.entity.TblAttachment;
import com.huabo.monitor.entity.TblOrganization;
import com.huabo.monitor.entity.TblReport;
import com.huabo.monitor.service.ITblAttachmentService;
import com.huabo.monitor.service.ITblReportService;
import com.huabo.monitor.service.PjbgService;
import com.huabo.monitor.service.PjjgService;
import com.huabo.monitor.util.ConstClass;
import com.huabo.monitor.util.DateUtils;
import com.huabo.monitor.util.ExportDoc;
import com.huabo.monitor.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.mockito.internal.matchers.Find;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@Slf4j
@Api(value = "内控合规报告-评价报告", tags = {"内控合规报告-评价报告所有接口"})
@RequestMapping(value = "/nbkz/pjbg")
public class PjbgController {

    @Resource
    PjbgService  pjbgService;

    @Resource
    ITblAttachmentService iTblAttachmentService;

    @Resource
    ITblReportService    iTblReportService;

    String type="nk";
    @Value("${filedir}")
    String filedir;
   /*
    public JsonBean listnkbg(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "type", value = "报告类型默认nk", defaultValue = "nk") @RequestParam(value = "type", required = false, defaultValue = "nk") String type,
            @ApiParam(name = "name", value = "报告名称") @RequestParam(value = "name", required = false)String name,
            @ApiParam(name = "startDate", value = "开始日期") @RequestParam(value = "startDate", required = false)String startDate,
            @ApiParam(name = "endDate", value = "结束日期") @RequestParam(value = "endDate", required = false)String endDate,
            @ApiParam(name = "fication", value = "fication") @RequestParam(value = "fication", required = false) String fication,
            @ApiParam(name = "view", value = "view") @RequestParam(value = "view", required = false) String view,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        IPage<TblReport> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        page = pjbgService.findAll(pageNumber,name,startDate,endDate, type, user.getCurrentOrg().getOrgid());

        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("type", type);
        mv.put("name", name);
        mv.put("startDate", startDate);
        mv.put("endDate", endDate);
        mv.put("fication", fication);
        mv.put("view", view);
        mv.put("pageBean", page);

        return new JsonBean(200, "success", mv);

    }
*/

    @ApiOperation("评价报告-主页")
    @GetMapping(value = "/nkbg/list")

    public JsonBean listnkbg(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,

            @ApiParam(name = "name", value = "报告名称") @RequestParam(value = "name", required = false)String name,
            @ApiParam(name = "startDate", value = "开始日期") @RequestParam(value = "startDate", required = false)String startDate,
            @ApiParam(name = "endDate", value = "结束日期") @RequestParam(value = "endDate", required = false)String endDate,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        IPage<TblReport> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        page = pjbgService.findAll(pageNumber,name,startDate,endDate, type, user.getCurrentOrg().getOrgid());

        Map<String, Object> mv = new LinkedHashMap<>();

        mv.put("name", name);
        mv.put("startDate", startDate);
        mv.put("endDate", endDate);

        mv.put("pageBean", page);

        return new JsonBean(200, "success", mv);

    }
    @PostMapping(value = "/addupload")
    @ApiOperation("评价/自定义报告-添加页面-附件上传")
    public  JsonBean pjpf_upload(
            HttpServletRequest request,

            @ApiParam(name="file",value="附件上传entity",required=true) MultipartFile file,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);

        String fileName = file.getOriginalFilename();
        System.out.println("fileName---"+fileName);
        Map<String, Object> mv = new LinkedHashMap<>();
        if (fileName != null && fileName != "") {
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            String oldname = fileName.substring(0, fileName.lastIndexOf("."));
            String newname = fileName.replace(oldname, "00"+timeInMillis);
            System.out.println(file.getInputStream());
            long size = file.getSize();
            try {
                boolean flag = FtpUtil.uploadFile(newname, file.getInputStream());
                if (flag) {
                    log.info("上传成功");
                } else {
                    log.info("上传失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            TblAttachment a = new TblAttachment();
            a.setAttname(fileName);
            a.setAttpath(newname);
            a.setAttsize(new BigDecimal(size / 1024));
            a.setUploader(user.getUsername());
            a.setUploadtime(LocalDateTime.now());
            iTblAttachmentService.save(a);

            mv.put("attid",a.getAttid());
            mv.put("Attachment",a);

        }
        return new JsonBean(200, "上传成功", mv);

    }


    @PostMapping(value = "/updateupload")
    @ApiOperation("评价/自定义报告-修改页面(附件单独操作直接对应数据,保存修改时不修改附件)-附件上传")
    public  JsonBean pjpf_updateupload(
            HttpServletRequest request,
            @ApiParam(name = "reportid", value = "报告reportid") @RequestParam(value = "reportid") String reportid,
            @ApiParam(name="file",value="附件上传entity",required=true) MultipartFile file,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);

        String fileName = file.getOriginalFilename();
        System.out.println("fileName---"+fileName);
        Map<String, Object> mv = new LinkedHashMap<>();
        if (fileName != null && fileName != "") {
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            String oldname = fileName.substring(0, fileName.lastIndexOf("."));
            String newname = fileName.replace(oldname, "00"+timeInMillis);
            System.out.println(file.getInputStream());
            long size = file.getSize();
            try {
                boolean flag = FtpUtil.uploadFile(newname, file.getInputStream());
                if (flag) {
                    log.info("上传成功");
                } else {
                    log.info("上传失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            TblAttachment a = new TblAttachment();
            a.setAttname(fileName);
            a.setAttpath(newname);
            a.setAttsize(new BigDecimal(size / 1024));
            a.setUploader(user.getUsername());
            a.setUploadtime(LocalDateTime.now());
            //iTblAttachmentService.save(a);
            // 添加附件 和  中间表
            this.pjbgService.saveRepAtt(a,reportid);

            mv.put("attid",a.getAttid());
            mv.put("reportid",reportid);
            mv.put("Attachment",a);

        }
        return new JsonBean(200, "上传成功并加入关系表", mv);

    }




    /**
     * 如果报告名称有重复的返回1, 并且弹出"报告已经存在",并且不保存重复报告的信息
     *
     * @param
     * @return
     */
    @PostMapping(value = "/isExistAdd")
    @ApiOperation("评价/自定义报告-添加页面-保存(code:-1 报告名存在,code:200 成功)")
    public JsonBean isAddExistByname(
            @ApiParam(name = "type", value = "报告类型:评价=nk,自定义=nk_zdy") @RequestParam(value = "type") String type,
            @ApiParam(name = "reportname", value = "报告名称") @RequestParam(value = "reportname")String reportname,
            @ApiParam(name = "startdate", value = "报告日期") @RequestParam(value = "startdate")String startdate,
            @ApiParam(name = "attids", value = "附件ids-多值逗号分割") @RequestParam(value = "attids", required = false)String attids,
            @ApiParam(name = "reporttype", value = "报告类型") @RequestParam(value = "reporttype")String reporttype,
            @ApiParam(name = "reportmode", value = "报告方式") @RequestParam(value = "reportmode")String reportmode,
            @ApiParam(name = "reporter", value = "报告人realname") @RequestParam(value = "reporter")String reporter,
           // @ApiParam(name = "oid", value = "报告部门id") @RequestParam(value = "oid")String  oid,
            @ApiParam(name = "reportdepartment", value = "报告部门名称") @RequestParam(value = "reportdepartment")String  reportdepartment,
            @ApiParam(name = "describe", value = "describe") @RequestParam(value = "describe", required = false)String  describe,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        LocalDateTime  lt=DateUtils.StringToLocalDateTime(startdate,"yyyy-MM-dd");
        QueryWrapper<TblReport> qw=new QueryWrapper<>();
        qw.eq("reportname",reportname);
        qw.eq("reporttime", lt);
        long count = this.iTblReportService.count(qw);
        Integer existByNum = 0;

        if (count > 0) {
            return new JsonBean(-1, "报告已存在","报告已存在" );
        } else {
            Map<String, Object> mv = new LinkedHashMap<>();
            TblReport report=new TblReport();
            report.setType(type);
            report.setReportname(reportname);
            report.setReporttime(lt);
            report.setReporttype(reporttype);
            report.setReportmode(reportmode);
            report.setReporter(reporter);
            report.setReportdepartment(reportdepartment);
            report.setRepdesc(describe);

            report.setOrgid(user.getCurrentOrg().getOrgid());

            this.pjbgService.saveReport(report,attids);
            mv.put("reportid",report.getReportid());
            mv.put("report",report);

            List<TblAttachment> list=pjbgService.getRepAttByReportId(report.getReportid());
            mv.put("atts",list);
            return new JsonBean(200, "保存成功", mv);
        }


    }

    @ApiOperation("评价/自定义报告-点击修改/详情查询")
    @GetMapping(value = "/nkbg/modify")
    public JsonBean modifynkbg(
            @ApiParam(name = "id", value = "reportid") @RequestParam(value = "id") String id,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        final TblReport report = this.iTblReportService.getById(id);
        if(report==null){
            return new JsonBean(-1, "数据不存在,请正确传值", "");
        }
        List<TblAttachment> list=pjbgService.getRepAttByReportId(report.getReportid());

        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("report",report);
        mv.put("atts",list);
        return new JsonBean(200, "success", mv);
    }


    @ApiOperation("评价/自定义报告-添加页面-附件删除")
    @PostMapping(value = "/add/sp_del_fj")
    public JsonBean addsp_del_fj(
            @ApiParam(name = "attid", value = "单个附件id") @RequestParam(value = "attid") BigDecimal attid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        this.iTblAttachmentService.removeById(attid);
        return new JsonBean(200, "success", "删除成功");
    }


    @ApiOperation("评价/自定义报告-修改页面(附件单独操作直接对应数据,保存修改时不修改附件)-附件删除")
    @PostMapping(value = "/update/sp_del_fj")
    public JsonBean updatesp_del_fj(

            @ApiParam(name = "attid", value = "单个附件id") @RequestParam(value = "attid") BigDecimal attid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        this.pjbgService.delAttAndRepAtt(attid,null);
        return new JsonBean(200, "success", "删除附件成功");
    }



    /**
     * 如果报告名称有重复的返回1, 并且弹出"报告已经存在",并且不保存重复报告的信息
     *
     * @param
     * @return
     */
    @PostMapping(value = "/isExistUpdate")
    @ApiOperation("评价/自定义报告-修改页面-保存(code:-1 报告名存在,code:200 成功,修改时不传附件信息)")
    public JsonBean isUpdateExistByname(
            @ApiParam(name = "reportid", value = "reportid") @RequestParam(value = "reportid") BigDecimal reportid,
            @ApiParam(name = "type", value = "报告类型:评价=nk,自定义=nk_zdy") @RequestParam(value = "type") String type,
            @ApiParam(name = "reportname", value = "报告名称") @RequestParam(value = "reportname")String reportname,
            @ApiParam(name = "startdate", value = "报告日期") @RequestParam(value = "startdate")String startdate,
            @ApiParam(name = "reporttype", value = "报告类型") @RequestParam(value = "reporttype")String reporttype,
            @ApiParam(name = "reportmode", value = "报告方式") @RequestParam(value = "reportmode")String reportmode,
            @ApiParam(name = "reporter", value = "报告人realname") @RequestParam(value = "reporter")String reporter,
            // @ApiParam(name = "oid", value = "报告部门id") @RequestParam(value = "oid")String  oid,
            @ApiParam(name = "reportdepartment", value = "报告部门名称") @RequestParam(value = "reportdepartment")String  reportdepartment,
            @ApiParam(name = "describe", value = "describe") @RequestParam(value = "describe", required = false)String  describe,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        LocalDateTime  lt=DateUtils.StringToLocalDateTime(startdate,"yyyy-MM-dd");
        QueryWrapper<TblReport> qw=new QueryWrapper<>();
        qw.eq("reportname",reportname);
        qw.eq("reporttime", lt);
        long count = this.iTblReportService.count(qw);
        Integer existByNum = 0;

        if (count > 0) {
            return new JsonBean(-1, "报告已存在","报告已存在" );
        } else {
            Map<String, Object> mv = new LinkedHashMap<>();
            TblReport report=this.iTblReportService.getById(reportid);
            //report.setReportid(reportid);
            report.setType(type);
            report.setReportname(reportname);
            report.setReporttime(lt);
            report.setReporttype(reporttype);
            report.setReportmode(reportmode);
            report.setReporter(reporter);
            report.setReportdepartment(reportdepartment);
            report.setRepdesc(describe);

            report.setOrgid(user.getCurrentOrg().getOrgid());
            this.iTblReportService.updateById(report);
           // this.pjbgService.saveReport(report,attids);
            mv.put("reportid",report.getReportid());
            mv.put("report",report);

            List<TblAttachment> list=pjbgService.getRepAttByReportId(report.getReportid());
            mv.put("atts",list);
            return new JsonBean(200, "保存成功", mv);
        }


    }




    @ApiOperation("评价/自定义报告-导出word")
    @GetMapping(value = "/sjss/expReportFile")
    public void expWordFile(
            HttpServletResponse response,
            @ApiParam(name = "reportid", value = "reportid") @RequestParam(value = "reportid") BigDecimal reportid
    )  {

        TblReport report = this.iTblReportService.getById(reportid);

        String fileNameStr = report.getReportname()+".doc";
        String folderPath = this.filedir;
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String fileName = folderPath + "/" + uuid + ".doc";
        System.out.println("fileName---" + fileName);
        ExportDoc exportDoc=new ExportDoc();

        Map dataMap=new HashMap();
        dataMap.put("repdesc",report.getRepdesc());
        exportDoc.createDoc("static.ftl", fileName, dataMap);
        // 导出Word
        FileUtil.downLoad(fileName, response, false, fileNameStr);

        FileUtil.deleteFile(fileName);
    }

    @ApiOperation("评价/自定义报告-删除")
    @PostMapping(value = "/nkbg/delete")
    public JsonBean deletenkbg(
            @ApiParam(name = "ids", value = "报告ids-多值用逗号分割") @RequestParam(value = "ids") String ids,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        this.pjbgService.delReport(ids);

        return new JsonBean(200, "删除成功", "删除成功");
    }


}
